import { Component } from '@angular/core';
import { TabsPage } from '../tabs/tabs.component';
import { LockPage } from '../lock/lock.component';
import { Device } from '@ionic-native/device';
import { Storage } from '@ionic/storage';
import { NgForm } from '@angular/forms';
import { Http } from '@angular/http';
import { AuthHttp } from 'angular2-jwt';
import { Config } from '../../providers/config';
import { AlertController, NavController, Platform, LoadingController, App, NavParams } from 'ionic-angular';
import _ from 'lodash';

@Component({
	selector: 'page-login',
	templateUrl: 'login.html'
})
export class LoginPage {
	moa_page_name: any = "page-login";
	moa_page_explain: any = "登录";

	login: { username?: string, username2?: string, password?: string, code?: string, cid?: string } = {};
	submitted = false;
	loading;
	isEnableGesturePassword = false;
	isEditusername = false;
	isEditcode = false;
	getCodeTime = 60;
	isEditpassword = false;
	// 是否显示获取验证码按钮
	isShowGetCodeBtn = true;
	// 是否需要验证码
	isNeedCaptcha = false;
	// 是否检测手势密码
	isCheckLockPassword = true;

	tempUsername = "";
	constructor(
		public alertController: AlertController,
		public loadingController: LoadingController,
		public platform: Platform,
		public authHttp: AuthHttp,
		public navParams: NavParams,
		public appCtrl: App,
		public config: Config,
		public nav: NavController,
		public device: Device,
		public http: Http,
		public storage: Storage
	) {
		console.info(this.navParams.data);
		this.isCheckLockPassword = this.navParams.data.hasOwnProperty("isCheckLockPassword") ? this.navParams.data.isCheckLockPassword : this.isCheckLockPassword;
		console.info('------------login page-----------');
		if (this.config.isProduct) {
			// 如果是生产,先检查token是否存在，再检测是否有手势密码，如果有则直接刷新token，如果没有，则重新登录
			this.storage.get('id_token').then((token) => {
				if (token) {
					this.storage.get('lockPassword').then((lockPassword) => {
						if (lockPassword) {
							if (this.isCheckLockPassword) {
								this.isEnableGesturePassword = true;
								// this.appCtrl.getRootNav().setRoot(LockPage);
								// 刷新本地token
								this.refreshToken();
								// this.nav.setRoot(LockPage);
							}
						} else {
							this.storage.remove('id_token').then(() => {
								console.info('remove token');
							});
						}
					});
				}
			});
		} else {
			this.refreshToken();
		}
		console.info('-------init login page-------')
		this.storage.get('userInfo').then((userInfo) => {
			if (userInfo) {
				this.login.username = userInfo.loginid;
			}
		});

		// 如果不是生产环境，自动把密码填上
		if (!this.config.isProduct) {
			this.login.password = 'test\@gfjj';
		}
		// this.refreshToken();
	}

	/**
	 * 如果输入的用户名和获取验证码的用户名一致，则提示需要验证码
	 */
	usernameChange() {
		if (this.login.username && (this.login.username === this.tempUsername)) {
			this.isNeedCaptcha = true;
		} else {
			this.isNeedCaptcha = false;
		}
	}

	refreshToken() {
		// 如果本地有token，则刷新token
		this.storage.get('id_token').then(token => {
			if (token) {
				this.auth('token', {});
			}
		});
	};

	cleanInput(type) {
		console.info(type);
		this.login[type] = "";
		console.info(this.login[type]);
	}

	focusInInput(type) {
		this["isEdit" + type] = true;
	}

	focusOutInput(type) {
		let that = this;
		setTimeout(function () {
			that["isEdit" + type] = false;
		}, 500);
	}

	invokeLogin(type, body) {
		let postUrl = '';
		let _httpClient;
		console.info(type);
		console.info(body);
		if (type == 'token') {
			postUrl = this.config.server + "api/v1/users/login/token";
			_httpClient = this.authHttp;
		} else if (type == 'fpassword') {
			postUrl = this.config.server + "api/v1/users/flogin/password";
			_httpClient = this.http;
		} else {
			postUrl = this.config.server + "api/v1/users/login/password";
			_httpClient = this.http;
		}
		_httpClient.post(postUrl, body).subscribe(result => {
			this.loading.dismiss();
			// 设置用户token
			result = result.json();
			console.info(result);
			// 保存token和用户名称
			this.storage.set('id_token', result.token).then(() => {
				this.storage.set('userInfo', result.userInfo).then(() => {
					this.storage.set('configs', result.configs).then(() => {
						this.storage.set("myMenu", result.userInfo.menu);
						console.info('----------login-------');
						// this.appCtrl.getRootNav().push(TabsPage);
						if (this.isEnableGesturePassword) {
							this.appCtrl.getRootNav().setRoot(LockPage);
							// this.nav.setRoot(LockPage);
						} else {
							this.appCtrl.getRootNav().setRoot(TabsPage);
							// this.nav.setRoot(TabsPage);
						}
					});
				});
			});
		}, err => {
			console.info(err);
			var errmsg = err.json();
			if (errmsg && ((errmsg.error).indexOf("请输入验证码") > -1)) {
				this.isNeedCaptcha = true;
			}
			let tips = '';
			if (err.status == 0) {
				tips = '网络连接出错,请检查你的网络状态';
			} else if (err.status == 500) {
				tips = errmsg.error;
			} else if (err.status == 401) {
				tips = errmsg.error;
			} else {
				tips = '系统发生一个错误,请稍后重试!';
			}
			let alert = this.alertController.create({
				title: '提示',
				subTitle: tips,
				buttons: ['确认']
			});
			alert.present();
			this.loading.dismiss();
		});
	}

	intervalGetCodeTime() {
		let that = this;
		setTimeout(function () {
			if (that.getCodeTime == 0) {
				that.isShowGetCodeBtn = true;
			} else {
				that.getCodeTime = that.getCodeTime - 1;
				that.intervalGetCodeTime();
			}
		}, 1000);
	};

	getCode() {
		let tips = '';
		if (!this.login.username) {
			tips = '请输入账号';
		}
		if (tips) {
			let alert = this.alertController.create({
				title: '提示',
				subTitle: tips,
				buttons: ['确认']
			});
			alert.present();
			return false;
		}
		let codeLoading = this.loadingController.create({
			content: '正在获取验证码...'
		});
		codeLoading.present();
		this.http.post(this.config.server + "api/v1/captchas/sms", {
			"username": this.login.username,
			"type": "login"
		}).subscribe(result => {
			this.tempUsername = this.login.username;

			result = result.json();
			this.login.cid = result['id'];
			codeLoading.dismiss();
			this.isShowGetCodeBtn = false;
			this.getCodeTime = 60;
			this.intervalGetCodeTime();

			let alert = this.alertController.create({
				title: '提示',
				subTitle: '已发验证码到尾号为：' + result['mobile'] + '的手机号码中',
				buttons: ['确认']
			});
			alert.present();
		}, err => {
			var errmsg = err.json();
			let alert = this.alertController.create({
				title: '提示',
				subTitle: errmsg.error,
				buttons: ['确认']
			});
			alert.present();
			codeLoading.dismiss();
		});
	};

	getVersionInfo() {
		let promise = new Promise(function (resolve, reject) {
			let version: any = {};
			window['chcp'].getVersionInfo(function (err, version) {
				version.appVersion = version.appVersion;
				version.h5Version = version.currentWebVersion;
				resolve(version);
			});
		});
		return promise;
	}

	auth(type, body) {
		this.loading = this.loadingController.create({
			content: '正在校验安全信息,请稍后...'
		});
		this.loading.present();
		let that = this;
		if (this.platform.is('cordova')) {
			body.platform = this.device.platform;
			body.uuid = this.device.uuid;
			body.model = this.device.model;
			body.phoneVersion = this.device.version;
			// 获取推送token
			that.storage.get('registrationId').then(registrationId => {
				body.pushToken = registrationId;
				// 获取应用版本信息
				that.getVersionInfo().then(function (version: any) {
					body.appVersion = version.appVersion;
					body.h5Version = version.h5Version;
					that.invokeLogin(type, body);
				});
			});
		} else {
			body.appVersion = '0.0.1';
			body.h5Version = '0.0.1';
			body.platform = 'browser';
			body.uuid = '1';
			body.model = 'web';
			body.phoneVersion = '1.0.0';
			that.invokeLogin(type, body);
		};
	}

	onLogin(form: NgForm) {
		sessionStorage.setItem('logonname',this.login.username);
		// 将logid 转换成小写，
    this.login.username = _.toLower(this.login.username);
    sessionStorage.setItem('key',this.login.username);
		this.submitted = true;
		if (form.valid) {
			if (this.login.username2) {
				this.auth('fpassword', this.login);
			} else {
				this.auth('password', this.login);
			}
		}
	}
}
